import 'dart:async';
import 'dart:collection';
import 'dart:math';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/choose_department_or_class/choose_filter_department_class_dialog.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/unallocated_department_staff_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/unallocated_department_view_model.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/stitching_avatar_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'add_or_edit_department_page.dart';
import 'class_or_department_detail.dart';
import 'class_or_department_viewmodel.dart';
import 'event/admin_change_event.dart';

///企业主页 班级或部门页面
/// type 类型 :[TYPE_DEPARTMENT]
/// [TYPE_CLASS]
///
class ClassOrDepartmentPage extends StatefulWidget {
  static const String ROUTER = 'ClassOrDepartmentPage';
  static const int TYPE_DEPARTMENT = 0;
  static const int TYPE_CLASS = 1;

  ///页面类型
  final int type;

  const ClassOrDepartmentPage({Key key, this.type}) : super(key: key);

  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context, int type) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      ClassOrDepartmentPage(
        type: type,
      ),
      routeName: ClassOrDepartmentPage.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return ClassOrDepartmentPageState();
  }
}

class ClassOrDepartmentPageState extends BasePagerState<DepartmentOrClassListItemBean, ClassOrDepartmentPage> {
  ClassOrDepartmentViewModel _viewModel;
  StreamSubscription streamSubscription;
  StreamSubscription streamSubscriptionDetail;

  @override
  void initState() {
    _viewModel = ClassOrDepartmentViewModel(this);
    super.initState();

    streamSubscriptionDetail =
        VgEventBus.global.streamController.stream.listen((event) {
      if (event is RefreshCompanyDetailPageEvent) {
        print('刷新班级部门信息：${event.msg}');
        _viewModel.refresh();
      }
      if (event is AdminChangeEvent) {
        print('ClassOrDepartmentPageState' + event.toString());
        _viewModel.refresh();
      }
    });

    streamSubscription = VgEventBus.global
        .on<UpdateUnallocatedInfoRefreshEvent>()
        .listen((event) {
      _viewModel.refresh();
      setState(() {});
    });
    _viewModel.refresh();
  }

  @override
  void dispose() {
    super.dispose();
    streamSubscription.cancel();
    streamSubscriptionDetail.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: <Widget>[
            _toTopBarWidget(),
            Expanded(
              child: VgPlaceHolderStatusWidget(
                loadingStatus: data == null,
                child: NestedScrollView(
                  headerSliverBuilder: (context, bool) {
                    return [
                      (data == null ||
                          data.length == 0 &&
                              StringUtils.isEmpty(_viewModel.keyword))
                          ? SliverToBoxAdapter(
                        child: SizedBox(),
                      )
                          : SliverPersistentHeader(
                        delegate:
                        CommonSliverPersistentHeaderDelegate(
                            child: Container(
                              color: ThemeRepository.getInstance()
                                  .getCardBgColor_21263C(),
                              padding: EdgeInsets.symmetric(
                                  vertical: 10),
                              child: CommonSearchBarWidget(
                                hintText: "搜索",
                                onChanged: (keyword) {
                                  _viewModel.keyword = keyword;
                                  _viewModel.refresh();
                                },
                                onSubmitted: (keyword) {
                                  _viewModel.keyword = keyword;
                                  _viewModel.refresh();
                                },
                              ),
                            ),
                            maxHeight: 50,
                            minHeight: 50),
                      )
                    ];
                  },
                  body: VgPlaceHolderStatusWidget(
                    loadingStatus: data == null,
                    emptyStatus: data?.isEmpty ?? false,
                    child: ScrollConfiguration(
                      behavior: MyBehavior(),
                      child: VgPullRefreshWidget.bind(
                          state: this,
                          viewModel: _viewModel,
                          child: ListView.builder(
                            padding: EdgeInsets.zero,
                            itemBuilder: (context, index) {
                              return _listItem(index);
                            },
                            itemCount: data == null ? 0 : data.length,
                          )) ,
                    ),
                  ),
                ),
              ),
            ),
            _showUnassignedBar(),
          ],
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      title:
          (widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT) ? "部门" : "班级",
      titleFontSize: 17,
      isShowBack: true,
      isHideRightWidget: !AppOverallDistinguish.comefromAiOrWeStudy() &&(widget?.type!=ClassOrDepartmentPage.TYPE_DEPARTMENT),
      rightWidget: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          //新增部门/班级
          DepartmentOrClassListItemBean result =
              await AddOrEditClassDepartmentPage.navigatorPush(
                  context, widget.type, false);
          //列表新增数据
          _viewModel.refresh();
        },
        child: Visibility(
          visible: VgRoleUtils.isSuperAdmin(
              UserRepository.getInstance().getCurrentRoleId()),
          child: Container(
            height: 44,
            alignment: Alignment.center,
            child: Text(
              "+新增",
              style: TextStyle(color: Color(0xFF1890FF), fontSize: 14),
              textAlign: TextAlign.left,
            ),
          ),
        ),
      ),
    );
  }

  _listItem(int index) {
    DepartmentOrClassListItemBean item = data[index];
    int adminCnt = item?.adminCnt ?? 0;
    String adminName = ((item?.adminName ?? '').split(',') ?? []).first;
    // List<String> urlList = item?.picurls?.split(',') ?? [];
    // urlList.removeWhere((element) => StringUtils.isEmpty(element));
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        //详情
        await ClassOrDepartmentDetail.navigatorPush(context, item, widget.type);
      },
      onLongPress: () {
        if(!AppOverallDistinguish.comefromAiOrWeStudy() && widget?.type!=ClassOrDepartmentPage.TYPE_DEPARTMENT){return;}
        if (!VgRoleUtils.isSuperAdmin(
            UserRepository.getInstance().getCurrentRoleId())) {
          return;
        }
        Map<String, VoidCallback> menuMap = {};
        menuMap['编辑'] = () async {
          //编辑部门/班级
          DepartmentOrClassListItemBean result =
              await AddOrEditClassDepartmentPage.navigatorPush(
                  context, widget.type, true,
                  oldBean: item);
          _viewModel.refresh();
        };

        menuMap['删除'] = () async {
          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(
              context,
              title: "提示",
              content: widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT
                  ? "确定删除${item.department ?? ''}？删除部门不会删除部门下的人员"
                  : "确定删除${item.classname ?? ''}？删除班级不会删除班级下的人员",
              cancelText: "取消",
              confirmText: "确定删除",
              confirmBgColor: Color(0xff1890ff));
          if (result ?? false) {
            _viewModel.delete(
                item,
                BaseCallback(onSuccess: (val) {
                  loading(false);
                  //成功后刷新企业详情
                  VgEventBus.global
                      .send(RefreshCompanyDetailPageEvent(msg: '删除部门或班级'));
                }, onError: (msg) {
                  toast(msg);
                }));
          }
        };

        CommonMoreMenuDialog.navigatorPushDialog(context, menuMap);
      },
      child: Container(
        height: 60,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 11),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  height: 36,
                  width: 36,
                  child: VgCacheNetWorkImage(
                    item?.dpPicurl??"",
                    fit: BoxFit.cover,
                    imageQualityType: ImageQualityType.middleDown,
                    defaultErrorType: ImageErrorType.head,
                    defaultPlaceType: ImagePlaceType.head,
                    emptyWidget: Container(
                      width: 36,
                      height: 36,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        border: Border.all(color: Color(0xffd0e0f7), width: 1),
                      ),
                      child: Image.asset(
                        "images/icon_default_depart_logo.png",
                        width: 36,
                        height: 36,
                      ),
                    ),
                  ),
                ),
              ),
              // StitchingAvatarWidget(
              //   avatarUrlList: urlList,
              //   emptyWidget: Container(
              //     width: 36,
              //     height: 36,
              //     decoration: BoxDecoration(
              //       borderRadius: BorderRadius.all(Radius.circular(4)),
              //       border: Border.all(color: Color(0xffd0e0f7), width: 1),
              //     ),
              //     child: Image.asset(
              //       "images/icon_default_depart_logo.png",
              //       width: 36,
              //       height: 36,
              //     ),
              //   ),
              // ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: Stack(
                  children: <Widget>[
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            //名称
                            Expanded(
                              child: Text(
                                '${VgStringUtils.subStringAndAppendSymbol(
                                    item?.getName(), 15,
                                    symbol: "...") ?? '暂无'}',
                                style: TextStyle(
                                    fontSize: 15, color: Color(0xffd0e0f7)),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            SizedBox(width: 2,),
                            //右侧管理员数，没有则不显示
                            ConstrainedBox(
                              constraints: BoxConstraints(minWidth: 100),
                                child: managerWidget(adminCnt, adminName)),
                          ],
                        ),
                        Spacer(),
                        Container(
                          //左侧显示成员数和刷脸数
                          child: Container(
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                RichTextWidget(
                                  fontSize: 12,
                                  contentMap: LinkedHashMap.from({
                                    '${widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '成员' : '学员'}':
                                        Color(0xff5e687c),
                                    '${item.memberCnt}':
                                        (item?.memberCnt ?? 0) > 0
                                            ? ThemeRepository.getInstance()
                                                .getPrimaryColor_1890FF()
                                            : Color(0xff5e687c),
                                    '人': Color(0xff5e687c)
                                  }),
                                ),
                                Visibility(
                                  visible: (item.faceCnt ?? 0) > 0,
                                  child: RichTextWidget(
                                    fontSize: 12,
                                    contentMap: LinkedHashMap.from({
                                      '，今日刷脸': Color(0xff5e687c),
                                      '${item.faceCnt ?? 0}':
                                          ThemeRepository.getInstance()
                                              .getPrimaryColor_1890FF(),
                                      '人': Color(0xff5e687c),
                                    }),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///管理员
  Visibility managerWidget(int adminCnt, String adminName) {
    return Visibility(
      visible: adminCnt > 0,
      child: Container(
        height: 14,
        alignment: Alignment.bottomRight,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Image.asset(
              "images/guanliyuan.png",
              width: 10,
              height: 11,
            ),
            SizedBox(
              width: 4,
            ),
            Text(
                '${adminCnt == 0 ? '' : (adminCnt > 1 ? '${adminName ?? ''}等$adminCnt人' : adminName ?? '0')}',
                maxLines: 1,
                style: TextStyle(
                  fontSize: 10,
                  height: 1.2,
                  color: VgColors.INPUT_BG_COLOR,
                )),
          ],
        ),
      ),
    );
  }

  ///未分配部门/班级是显示条
  _showUnassignedBar() {
    return StreamBuilder(
      stream: _viewModel.cntStream?.stream,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        int cnt = 0;
        if (snapshot.connectionState == ConnectionState.active) {
          if (snapshot.data != null) {
            cnt = snapshot.data;
          }
        }
        return Visibility(
          visible: (cnt ?? 0) > 0 &&
              VgRoleUtils.isSuperAdmin(
                  UserRepository.getInstance().getCurrentRoleId()),
          child: GestureDetector(
            onTap: () {
              UnallocatedDepartmentStaffWidget?.navigatorPush(
                  context, widget.type);
            },
            child: Container(
              height: 50,
              width: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 15),
              color: Color(0xfff95355).withOpacity(0.2),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '未分配${widget.type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '部门' : '班级'}：$cnt人',
                      style: TextStyle(color: Color(0xfff95355), fontSize: 15),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: Image.asset(
                      "images/go_ico.png",
                      width: 6,
                      color: VgColors.INPUT_BG_COLOR,
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
